package com.quan.weixin.web.controller.boss;

import java.net.URLEncoder;

import javax.validation.Valid;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.quan.base.common.base.web.support.BaseResult;
import com.quan.base.common.base.web.support.controller.BaseController;
import com.quan.base.common.utils.Paginator;
import com.quan.upms.annotation.RequiresPermissions;
import com.quan.weixin.common.WeixinContext;
import com.quan.weixin.model.SubscribeUser;
import com.quan.weixin.model.UserDetail;
import com.quan.weixin.rpc.api.WeixinApiService;
import com.quan.weixin.rpc.api.WeixinSubscribeUserService;
import com.quan.weixin.rpc.model.WeixinSubscribeUser;

@RestController
@RequestMapping(value = "/api/weixin/subscribe_user")
public class WeixinSubscribeUserController extends BaseController {

	@Autowired
	private WeixinSubscribeUserService weixinSubscribeUserService;
	
	@Autowired
	private WeixinApiService weixinApiService;
	
	@RequiresPermissions(value="weixin:subscribe_user:add", description="添加微信关注用户消息")
	@PostMapping(value = "/add")
	public Object add(@Valid @RequestBody WeixinSubscribeUser entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
            return BaseResult.failure(bindingResult.getFieldError().getDefaultMessage()) ;
        }
		this.weixinSubscribeUserService.insertSelective(entity);

		return BaseResult.ok();
	}

	@RequiresPermissions(value="weixin:subscribe_user:delete", description="删除微信关注用户消息")
	@GetMapping(value = "/delete/{id}")
	public Object delete(@PathVariable Integer id) {
		this.weixinSubscribeUserService.delete(id);
		return BaseResult.ok();
	}
	
	@RequiresPermissions(value="weixin:subscribe_user:delete", description="删除微信关注用户消息")
	@GetMapping(value = "/deleteBatch")
	public Object deleteBatch(String ids) {
		this.weixinSubscribeUserService.deleteByIds(ids) ;
		return BaseResult.ok();
	}

	@RequiresPermissions(value="weixin:subscribe_user:update", description="修改微信关注用户消息")
	@PostMapping(value = "/update")
	public Object update(@Valid @RequestBody WeixinSubscribeUser entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
            return BaseResult.failure(bindingResult.getFieldError().getDefaultMessage()) ;
        }
		this.weixinSubscribeUserService.update(entity);
		return BaseResult.ok();
	}

	@RequiresPermissions(value="weixin:subscribe_user:detail", description="查询微信关注用户消息详情")
	@GetMapping(value = "/get/{id}")
	public Object list(@PathVariable Integer id) {
		return this.weixinSubscribeUserService.selectById(id);
	}
	
	@RequiresPermissions(value="weixin:subscribe_user:list", description="查询微信关注用户消息")
	@GetMapping(value = "/list")
	public Object list(WeixinSubscribeUser entity) {
		return this.weixinSubscribeUserService.selectPage(new Paginator(request), entity) ;
	}
	
	/**
	 * 同步远程微信用户列表
	 * @param entity
	 * @return
	 */
	@RequiresPermissions(value="weixin:subscribe_user:sync", description="同步远程微信用户列表")
	@GetMapping(value = "/syncUserList")
	public Object synchronizationUserList(WeixinSubscribeUser entity) {
		sync(new SubscribeUser());
		return BaseResult.ok() ;
	}
	
	public void sync(SubscribeUser sync) {
		SubscribeUser subscribeUserList = this.weixinApiService.getSubscribeUserList(WeixinContext.getAccessToken(), sync.getNext_openid()) ;
		logger.info("关注该公众账号的总用户数：{}", subscribeUserList.getTotal());
		logger.info("拉取的OPENID个数，最大值为10000：{}", subscribeUserList.getCount());
		logger.info("列表数据，OPENID的列表：{}", subscribeUserList.getData());
		logger.info("拉取列表的最后一个用户的OPENID：{}", subscribeUserList.getNext_openid());
		
		if(null != subscribeUserList.getData()) {
			for (String openid : subscribeUserList.getData()) {
				if(this.weixinSubscribeUserService.checkValue("openid", openid) != null) {
					continue ;
				}
				UserDetail userDetail = this.weixinApiService.getUserDetail(WeixinContext.getAccessToken(), openid) ;
				System.out.println(openid+"==>"+userDetail);
				
				try {
					WeixinSubscribeUser entity = new WeixinSubscribeUser() ;
					BeanUtils.copyProperties(userDetail, entity);
					entity.setNickname(URLEncoder.encode(entity.getNickname(), "utf-8"));
					entity.setSubscribeTime(userDetail.getSubscribe_time());
					entity.setTagidList(JSON.toJSONString(userDetail.getTagid_list()));
					entity.setHeadimgurl(userDetail.getHeadimgurl() != null ? userDetail.getHeadimgurl().replaceAll("/132", "/46") : null);
					this.weixinSubscribeUserService.insertSelective(entity);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if(subscribeUserList.getNext_openid() != null) {
				sync(subscribeUserList);
			}
		}
		
	}
}
